package com.mbbb.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbbb.yygh.common.exception.YyghException;
import com.mbbb.yygh.common.utils.JwtHelper;
import com.mbbb.yygh.enums.AuthStatusEnum;
import com.mbbb.yygh.model.user.Patient;
import com.mbbb.yygh.model.user.UserInfo;
import com.mbbb.yygh.user.mapper.UserInfoMapper;
import com.mbbb.yygh.user.service.PatientService;
import com.mbbb.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbbb.yygh.vo.user.LoginVo;
import com.mbbb.yygh.vo.user.UserAuthVo;
import com.mbbb.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author mbbb
 * @since 2021-12-16
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    //认证审批   2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            this.updateById(userInfo);
        }
    }

    //用户详情（用户基本信息和就诊人信息）
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.getPatientList(userId);
        map.put("patientList",patientList);
        return map;
    }

    //用户的锁定和解锁
    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue()==0 || status.intValue()==1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    //用户列表（条件查询带分页）
    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String keyword = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like("name", keyword);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }

        //调用mapper的方法
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        userInfoPage.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return userInfoPage;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

    //认证更新
    @Override
    public void userAuthUpdate(Long userId , UserAuthVo userAuthVo) {
        //根据id查询
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证姓名
        userInfo.setName(userAuthVo.getName());
        //证件类型
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        //证件号
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        //证件路径
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //认证状态
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    //用户登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //1.获取登录需要的数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //2.判断数据是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001,"数据为空");
        }

        //3.验证码校验
        //从redis获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //和输入的验证码比对
        if (!code.equals(redisCode)) {
            throw new YyghException(20001,"验证码错误");
        }

        //获取openid
        String openid = loginVo.getOpenid();
        //判断openid值是否为空
        if (StringUtils.isEmpty(openid)) { //如果为空手机验证码登录，

            //4.判断是否为第一次登录，如果是第一次登录自动注册
            //根据手机号查询数据表，如果没查出来，就是第一次，把数据添加数据库完成注册
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }

            //5.用户是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001,"用户已被禁用");
            }

            //6.登录成功之后，返回需要数据
            Map<String, Object> map = getData(userInfo);
            return map;
        } else {  //如果不为空微信绑定手机号
            //1 根据手机号查询，表是否存在相同手机号数据
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo exeitPhone = baseMapper.selectOne(wrapper);
            //判断
            if(exeitPhone == null) { //表示不存在相同绑定手机号
                //根据openid获取微信信息
                UserInfo userInfoByOpenid1 = this.getUserInfoByOpenid(openid);
                if (userInfoByOpenid1 == null) {
                    throw new YyghException(20001,"微信信息不存在");
                }
                //设置绑定的手机号
                userInfoByOpenid1.setPhone(phone);
                //更新
                baseMapper.updateById(userInfoByOpenid1);

                Map<String, Object> map = getData(userInfoByOpenid1);
                return map;
            } else { //表示存在相同绑定手机号
                //根据openid获取微信数据
                UserInfo info = new UserInfo();
                info.setOpenid(openid);
                QueryWrapper<UserInfo> wrapper4 = new QueryWrapper<>(info);

                UserInfo selectOne = baseMapper.selectOne(wrapper4);
                //把相同手机号记录数据set到微信对象里面
                //设置绑定手机号
                selectOne.setPhone(exeitPhone.getPhone());
                //用户真实姓名
                selectOne.setName(exeitPhone.getName());
                //其他数据
                selectOne.setCertificatesType(exeitPhone.getCertificatesType());
                selectOne.setCertificatesNo(exeitPhone.getCertificatesNo());
                selectOne.setCertificatesUrl(exeitPhone.getCertificatesUrl());

                //删除手机号数据
                QueryWrapper<UserInfo> wrapperDelete = new QueryWrapper<>();
                wrapperDelete.eq("phone",exeitPhone.getPhone());
                baseMapper.delete(wrapperDelete);

                //更新
                baseMapper.updateById(selectOne);

                Map<String, Object> map = getData(selectOne);
                return map;
            }
        }
    }

    //根据openid获取微信信息
    private UserInfo getUserInfoByOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    //获取需要返回的数据
    private Map<String, Object> getData(UserInfo userInfo) {

        Map<String, Object> map = new HashMap<>();

        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name",name);
        //TODO 返回token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }
}
